import sys
sys.path.append("..")


from flask import Flask,request,render_template

import lib.config as config
from lib.model import StockLine, date2ts,ts2date
from lib.exts import db
from lib.bfredis.bfredis import bfredis

import redis

import json

app = Flask(__name__, 
            template_folder='./static',
            static_folder='./static',
            static_url_path="")

app.config.from_object(config)


db.init_app(app)

with app.app_context():
    db.create_all()

redis_pool = redis.ConnectionPool(host=config.REDIS_HOST, port=config.REDIS_PORT)
redis_handle = redis.StrictRedis(connection_pool=redis_pool, charset='utf-8')
cur_bf = bfredis(config.BF_KEY, redis_handle)
'''
tar_url = 'a'

if cur_bf.do_filter(tar_url):
    print('过滤')
else:
    print('不过滤')
'''

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/data/get_kline')
def get_kline():
    tar_code = request.args.get('code')
    tar_start = request.args.get('start')
    tar_end = request.args.get('end')
    
    start_ts = date2ts(tar_start)
    end_ts = date2ts(tar_end)
    
    res_query = db.session.query(StockLine).filter(StockLine.code==tar_code,StockLine.date>=start_ts,StockLine.date<=end_ts).order_by(StockLine.date).all()
    
    res_list = []
    date_list = []
    for item in res_query:
        #cur_item = item.to_json()
        date_list.append(ts2date(item.date))
        res_list.append([item.open,item.close,item.high,item.low])
    print(date_list)
    print(res_list)
    return json.dumps({'status':1, 'data':{'date': date_list, 'kline':res_list}})
    
    
    
    
   


if __name__ == '__main__':
    app.run(debug=False,host='0.0.0.0', port=25000)